package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.RoleMenu;
import com.itheima.health.pojo.RolePermission;
import com.itheima.health.service.RoleMenuService;
import com.itheima.health.service.RolePermissionService;
import com.itheima.health.service.RoleService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("rolestatus")
public class RoleStatusController {
    @DubboReference
    private RoleService roleService;
    @DubboReference
    private RolePermissionService rolePermissionService;
    @DubboReference
    private RoleMenuService roleMenuService;

    @GetMapping("findPage")
    public Result findPage(QueryPageBean queryPageBean) {
        PageResult pageResult = roleService.findPage(queryPageBean);
        return new Result(true, MessageConst.ACTION_SUCCESS, pageResult);
    }

    @RequestMapping("add")
    public Result add(@RequestBody Role role, Integer[] permissionIds, Integer[] menuIds) {
        roleService.add(role);
        Role role1 = roleService.findByName(role.getName());
        Integer roleId = role1.getId();
        RolePermission rolePermission = new RolePermission();
        rolePermission.setRoleId(roleId);
        for (Integer permissionId : permissionIds) {
            rolePermission.setPermissionId(permissionId);
            rolePermissionService.add(rolePermission);
        }
        RoleMenu roleMenu = new RoleMenu();
        roleMenu.setRoleId(roleId);
        for (Integer menuId : menuIds) {
            roleMenu.setMenuId(menuId);
            roleMenuService.add(roleMenu);
        }
        return new Result(true, MessageConst.ACTION_SUCCESS);
    }

    @GetMapping("findById")
    public Result findById(Integer id) {
        Role role = roleService.findById(id);
        return new Result(true, MessageConst.ACTION_SUCCESS, role);

    }

    @GetMapping("findpermissionIdsById")
    public Result findpermissionIdsById(Integer id) {
        List<Integer> permissionIds = rolePermissionService.findpermissionIdsById(id);
        return new Result(true, MessageConst.ACTION_SUCCESS, permissionIds);
    }

    @PostMapping("edit")
    public Result edit(@RequestBody Role role, Integer[] permissionIds, Integer[] menuIds) {
        roleService.edit(role);
        rolePermissionService.edit(role, permissionIds);
        roleMenuService.edit(role, menuIds);
        return new Result(true, MessageConst.ACTION_SUCCESS);

    }

    @GetMapping("delete")
    public Result delete(Integer id) {
        roleService.delete(id);
        return new Result(true, MessageConst.ACTION_SUCCESS);

    }
}
